package de.saumya.webfortune.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;

public class QuoteController {
  
  private final QuoteHTML quoteHTML;
  
  public QuoteController(QuoteHTML quoteHTML){
    this.quoteHTML = quoteHTML;
  }
  
  public void load(Quote quote){
    String url = GWT.getModuleBaseURL() + quote.file();
    RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);

    try {
        this.quoteHTML.setText("loading...");
        builder.sendRequest(null, new RequestCallback() {
        public void onError(Request request, Throwable exception) {
          quoteHTML.setHTML("<pre>" + exception.getMessage() + "</pre>");
        }

        public void onResponseReceived(Request request, Response response) {
          quoteHTML.setHTML(response.getText());
        }
      });
    } 
    catch (RequestException e) {
      this.quoteHTML.setHTML("<pre>" + e.getMessage() + "</pre>");
    }
  }

  public void hideQuotes() {
    quoteHTML.setVisible(false);
  }

  public void showQuotes() {
    quoteHTML.setVisible(true);
  }
 
}
